package com.miku.project.service.impl.inner;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.mikuapicommon.model.entity.UserInterfaceInvoke;
import com.miku.mikuapicommon.service.InnerUserInterfaceInvokeService;
import com.miku.project.common.ErrorCode;
import com.miku.project.exception.BusinessException;
import com.miku.project.mapper.UserInterfaceInvokeMapper;
import com.miku.project.service.InterfaceInfoService;
import com.miku.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@DubboService
@Slf4j
public class InnerUserInterfaceInvokeServiceImpl extends ServiceImpl<UserInterfaceInvokeMapper, UserInterfaceInvoke> implements InnerUserInterfaceInvokeService {

    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private UserService userService;
    /**
     * 援引
     * 接口调用
     * @param interfaceInfoId 接口信息id
     * @param userId          用户id
     * @param reduceScore     降低分数
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean invoke(Long interfaceInfoId, Long userId, Integer reduceScore) {

        UserInterfaceInvoke interfaceInvoke = this.getOne(Wrappers.<UserInterfaceInvoke>lambdaQuery()
                .eq(UserInterfaceInvoke::getInterfaceId, interfaceInfoId)
                .eq(UserInterfaceInvoke::getUserId, userId));
        //不存在就创建一条记录
        boolean invokeResult;
        if (interfaceInvoke == null){
            interfaceInvoke = new UserInterfaceInvoke();
            interfaceInvoke.setInterfaceId(interfaceInfoId);
            interfaceInvoke.setUserId(userId);
            interfaceInvoke.setTotalInvokes(1L);
            interfaceInvoke.setCreateTime(new Date());
            invokeResult = this.save(interfaceInvoke);
        }else {
            invokeResult = this.update(Wrappers.<UserInterfaceInvoke>lambdaUpdate()
                    .eq(UserInterfaceInvoke::getInterfaceId, interfaceInfoId)
                    .eq(UserInterfaceInvoke::getUserId, userId)
                    .setSql("totalInvokes=totalInvokes+1"));
        }
        //更新接口的总调用次数
        boolean totalInvokes = interfaceInfoService.updateTotalInvokes(interfaceInfoId);
        //更新用户钱包积分
        boolean addWalletBalance = userService.addWalletBalance(userId, reduceScore);
        boolean updateresult=invokeResult && totalInvokes && addWalletBalance;
        if (!updateresult){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
        }
        return true;
    }
}
